layui.define(function(exports) {
    var $ = layui.$,
      admin = layui.admin,
      setter = layui.setter,
      laytpl = layui.laytpl,
      element = layui.element
      hot = layui.hot,
      hotProductLibrary = layui.hotProductLibrary;

    var list = [];
    var sortArray = [];
    var categoryCode;

    function initList(categoryCode) {
      list = [];
      sortArray = [];
      let params = {
        categoryCode: categoryCode
      };
      
      if (sessionStorage.category==='CHANNEL'||sessionStorage.category==='CHANNEL_SUB_ACC') {
        params.isMall = 1;
      }else {
        params.isJhzb = 1;
      }

      admin.req({
        url: setter.url + '/product/getProductListMall',
        type: 'GET',
        data: params,
        done: function (res) {
          var data = res.data || [];
          list = data;
          renderData(list);
        }
      });
    }

    function initTab(callback) {
      admin.req({
        url: setter.url + '/product/selectProdCategoryNum',
        type: 'GET',
        done: function (res) {
          var data = res.data || [];
          categoryCode = data[0].categoryCode;
          renderTab(data);

          if (typeof(callback) == 'function') {
            callback();
          }
        }
      });
    }

    // 初始化方法
    function initEvents() {
      $('.LAY_product_center_btn_delete').off('click').on('click', function () {
        var productCode = $(this).data('code');
        layer.confirm('是否确定删除该产品?', function(index){
          updataData(0, productCode, function () {
            var centerProductLibrary = layui.centerProductLibrary
            centerProductLibrary.refresh();
            layer.close(index);
          });
        }); 
      });
      
      $('.LAY_product_center_btn_up').off('click').on('click', function () {
        var index = $(this).data('index');
        
        if (index <= 0) {
          return;
        }

        moveUp(index);
      });
      
      $('.LAY_product_center_btn_down').off('click').on('click', function () {
        var index = $(this).data('index');
        
        if (index >= (list.length - 1)) {
          return;
        }

        moveDown(index);
      });
    }

    // 上移
    function moveUp(oldIndex) {
      var newIndex = oldIndex - 1;
      list = updataSort(list, 'sort', newIndex, oldIndex);
      renderData(list);
      saveSetting();
    }

    // 下移
    function moveDown(oldIndex) {
      var newIndex = oldIndex + 1;
      list = updataSort(list, 'sort', newIndex, oldIndex);
      renderData(list);
      saveSetting();
    }

    // 重新排序
    function updataSort(targetArr, property, newIndex, oldIndex) {
      var clone = $.extend(true, [], targetArr);

      layui.each(clone, function (index, item) {
        delete item.active;
      });

      var cloneNew = $.extend(true, {}, clone[newIndex]);
      var cacheCloneNew = $.extend(true, {}, clone[newIndex]);
      var cloneOld = $.extend(true, {}, clone[oldIndex]);

      cloneNew[property] = cloneOld[property];
      cloneOld[property] = cacheCloneNew[property];
      cloneOld.active = true;

      cacheSortArray(cloneOld);
      cacheSortArray(cloneNew);

      clone.splice(newIndex, 1, cloneOld);
      clone.splice(oldIndex, 1, cloneNew);
      return clone;
    }

    // 缓存排序
    function cacheSortArray(target) {
      if (has(sortArray, target.productCode)) {
        for(var i = 0; i < sortArray.length; i ++) {
          if (sortArray[i].productCode == target.productCode) {
            $.extend(sortArray[i], target);
            return;
          }
        }
      } else {
        sortArray.push(target);
      }

      sortArray = $.extend(true, [], sortArray);

      layui.each(sortArray, function (index, item) {
        delete item.active;
      });
    }

    // 渲染数据
    function renderData(data, callback) { 
      var getTpl = $('#LAY_product_center_tpl').html();

      if (!getTpl) {
        return;
      }

      laytpl(getTpl).render(data, function(html){
        $('#LAY_product_center_view').html(html);

        if (data && data.length) {
          initEvents();
        }

        if (typeof(callback) === 'function') {
          callback();
        }
      });
    }

    // 查重
    function has(array, target) {
      var buffer = [];

      layui.each(array, function (index, item) {
        buffer.push(Number(item.productCode));
      });

      if (buffer.indexOf(Number(target)) > -1) {
        return true;
      }

      return false;
    }

    // 更新数据
    function updataData(value, productCode, callback) {
      var url = setter.url;
      if (sessionStorage.category==='CHANNEL'||sessionStorage.category==='CHANNEL_SUB_ACC') {
        url = url + '/product/updateIsMall';
      } else {
        url = url + '/product/updateIsJhzb';
      }

      admin.req({
        url: url,
        type: 'POST',
        data: {
          value: value,
          productCode: productCode
        },
        done: function () {
          initList(categoryCode);

          hot.init(function () {
            hotProductLibrary.refresh();
          });

          if (typeof(callback) == 'function') {
            callback();
          }
        }
      });
    }

    // 渲染tab
    function renderTab(data) { 
      var getTpl = $('#LAY_product_center_tab_tpl').html();

      if (!getTpl) {
        return;
      }
      
      laytpl(getTpl).render(data, function(html){
        $('#LAY_product_center_tab_view').html(html);
        initList(categoryCode);

        element.on('tab(LAY_product_center_tab)', function(){
          categoryCode = $(this).data('code');
          initList(categoryCode);
        });
      });
    }

    function addData(productCode) {
      updataData(1, productCode);
    }
    
    // 储存产品中心设置
    function saveSetting(callback) {
      admin.req({
        url: setter.url + '/product/productSort',
        type: 'POST',
        data: { 
          data: JSON.stringify(sortArray)
        },
        done: function () {
          sortArray = [];

          if (typeof(callback) == 'function') {
            callback();
          }
        }
      });
    }

    exports('center', {
      add: addData,
      init: initTab,
    });
});